﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace UnitConcentratorPickTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            SpaceTime--;
            toolStripLabel3.Text = string.Format("{0:D2}:{1:D2}", SpaceTime / 60, SpaceTime % 60);
            if (SpaceTime == 0)
            {               
                PickTemperature();                
                SpaceTime = 660;
                toolStripLabel3.Text = string.Format("{0:D2}:{1:D2}", SpaceTime / 60, SpaceTime % 60);
            }
        }
        int FloorCount;
        int RoomCount;
        int ModelCount;
        int SpaceTime;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {           
            if(toolStripButton1.Text=="开始采集")
            {
                FloorCount = Convert.ToInt32(toolStripTextBox3.Text);
                RoomCount = Convert.ToInt32(toolStripTextBox1.Text);
                ModelCount = Convert.ToInt32(toolStripTextBox2.Text);
                listView1.Clear();
                listView1.Columns.Add("序号", 50);
                for (int i = 0; i < FloorCount; i++)
                {
                    for (int j = 0; j < RoomCount; j++)
                    {
                        for (int k = 0; k < ModelCount; k++)
                        {
                            string str = (i + 1).ToString() + "0" + (j + 1).ToString() + "-" + (k + 1).ToString();
                            ColumnHeader ch = new ColumnHeader();
                            ch.Text = str;
                            ch.Width = 85;
                            ch.TextAlign = HorizontalAlignment.Center;
                            listView1.Columns.Add(ch);
                        }
                    }
                }
                StringBuilder strSave = new StringBuilder();
                strSave.Clear();
                strSave.AppendFormat("{0,-6}", "序号");
                strSave.AppendFormat("{0,-20}", "时间");
                for (int i = 0; i < FloorCount; i++)
                {
                    for (int j = 0; j < RoomCount; j++)
                    {
                        for (int k = 0; k < ModelCount; k++)
                        {
                            string str = (i + 1).ToString() + "0" + (j + 1).ToString() + "-" + (k + 1).ToString();
                            strSave.AppendFormat("{0,-15}", str);
                        }
                    }
                }
                FileStream fs = new FileStream(file, FileMode.Open);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                fs.Seek(0, SeekOrigin.End);
                sw.WriteLine(strSave.ToString());
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
                //PickTemperature();
                timer1.Enabled = true;
                SpaceTime = 2;
                toolStripLabel3.Text = string.Format("{0:D2}:{1:D2}", SpaceTime / 60, SpaceTime % 60);
                toolStripButton1.Text = "停止采集";
            }
            else
            {
                toolStripButton1.Text = "开始采集";
                timer1.Enabled = false;
            }
        }
        string file;
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            toolStripComboBox1.Items.Clear();
            toolStripComboBox1.Items.AddRange(ports);
            toolStripComboBox1.SelectedIndex = 0;
            file = System.Windows.Forms.Application.StartupPath + "\\Data\\采集数据" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".txt";            
            FileInfo f = new FileInfo(file);
            if (!Directory.Exists(f.DirectoryName))
                Directory.CreateDirectory(f.DirectoryName);
            FileStream fs = new FileStream(file, FileMode.Create);           
            fs.Close();
        }
        void PickTemperature()
        {
            StringBuilder strSave=new StringBuilder();
            ListViewItem li = listView1.Items.Add((listView1.Items.Count + 1).ToString());
            strSave.Clear();
            strSave.AppendFormat("{0,-6}", listView1.Items.Count.ToString());
            strSave.AppendFormat("{0,-20}", DateTime.Now.ToString());
            SerialPort _COM = null;
            _COM = new SerialPort(toolStripComboBox1.Text, 9600, Parity.None, 8, StopBits.One);
            _COM.ReadTimeout = 200;
            while (true)
            {
                try
                {
                    _COM.Open();
                    break;
                }
                catch
                {
                    if (MessageBox.Show("当前串口无法打开,是否重试", "通信错误", MessageBoxButtons.YesNo) == DialogResult.No)
                        return;
                }
            }
            for (int i = 0; i < FloorCount; i++)
            {
                int FloorRetry = 5;
                while (FloorRetry!=0)
                {                    
                    byte[] Tx = new byte[9];
                    Tx[0] = 0x16;
                    Tx[1] = 0x16;
                    Tx[2] = (byte)i;
                    Tx[3] = 0x01;
                    Tx[4] = 0x02;
                    Tx[5] = (byte)RoomCount;
                    Tx[6] = (byte)ModelCount;
                    Tx[7] = WFNetLib.Verify.GetVerify_byteSum(Tx, 7);
                    Tx[8] = 0x0d;
                    _COM.Write(Tx, 0, 9);
                    byte needLen = (byte)(RoomCount * ModelCount * 5 + 7);
                    byte[] RxList = new byte[RoomCount * ModelCount * 5+7];
                    int retry = 100;
                    byte RxCount = 0;
                    while (retry != 0)
                    {
                        try
                        {
                            RxList[RxCount++] = (byte)_COM.ReadByte();                           
                        }
                        catch/* (TimeoutException ex)*/
                        {
                            retry = 0;
                            break;
                        }
                        if (RxCount == 1)
                        {
                            if (RxList[0] != 0x16)
                            {
                                RxCount = 0;
                                retry--;
                            }
                        }
                        else if (RxCount == 2)
                        {
                            if (RxList[1] != 0x16)
                            {
                                RxCount--;
                                retry--;
                            }
                        }
                        else if (RxCount == 3)//地址
                        {
                            if (RxList[2] != (byte)(i))
                            {
                                RxCount--;
                                retry--;
                            }
                        }
                        else if (RxCount == 4)//命令
                        {
                            if (RxList[3] != 0x01)
                            {
                                RxCount--;
                                retry--;
                            }
                        }
                        else if (RxCount == 5)//长度
                        {
                            if (needLen != (byte)(RxList[4] + 7))
                            {
                                RxCount--;
                                retry--;
                            }
                        }
                        else if (RxCount > 6)//判断是否接收完成
                        {
                            if (RxCount == needLen && RxList[RxCount-1]==0x0d)//正确完成
                            {
                                if (WFNetLib.Verify.GetVerify_byteSum(RxList, RxCount - 2) == RxList[RxCount - 2])//校验正确
                                {
                                    for (int j = 0; j < RoomCount; j++)
                                    {
                                        for (int k = 0; k < ModelCount; k++)
                                        {
                                            int index = 5 + j * ModelCount * 5 + k*5;
                                            string str = string.Format("{0:X2}{1:X2},{2:X2}{3:X2},{4:X2}", RxList[index+1], RxList[index], RxList[index+3], RxList[index+2], RxList[index+4]);
                                            li.SubItems.Add(str);
                                            strSave.AppendFormat("{0,-15}", str);
                                        }
                                    }
                                    break;
                                }
                                else
                                {
                                    retry = 0;
                                    break;
                                }
                            }
                            else
                            {
                                if (RxCount > needLen)
                                {
                                    retry = 0;
                                    break;
                                }
                            }
                        }                        
                    }
                    if (retry != 0)
                        break;
                    FloorRetry--;
                }
                if (FloorRetry == 0)//获取数据失败
                {
                    for (int j = 0; j < RoomCount; j++)
                    {
                        for (int k = 0; k < ModelCount; k++)
                        {
                            int index = 5 + j * ModelCount * 5 + k * 5;
                            string str = "XXXX,XXXX,XX";
                            li.SubItems.Add(str);
                            strSave.AppendFormat("{0,-15}", str);
                        }
                    }
                }
            }
            _COM.Close();
            FileStream fs = new FileStream(file, FileMode.Open);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            fs.Seek(0, SeekOrigin.End);
            sw.WriteLine(strSave.ToString());
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();/**/
            listView1.Items[listView1.Items.Count - 1].Selected = true;
        }
    }
}
